﻿using System;
using System.Linq;
using System.Reflection;
using Admin2020.Core.Domain.Core;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.Extensions.Configuration;

namespace Admin2020.Core.Domain
{
    public class Admin2020DbContext:DbContext
    {
        public Admin2020DbContext(DbContextOptions<Admin2020DbContext> options):base(options)
        {
            this.ChangeTracker.StateChanged += ChangeTracker_StateChanged;
            //Database.EnsureCreated();//不存在表时会创建
        }

        private void ChangeTracker_StateChanged(object sender, EntityStateChangedEventArgs e)
        {
            //如果实体状态变为了EntityState.Modified，那么就尝试设置其UpdateTime属性为当前系统时间DateTime.Now，如果实体没有UpdateTime属性，会抛出InvalidOperationException异常，所以下面要用try catch来捕获异常避免系统报错
            if (e.NewState == EntityState.Modified)
            {
                e.Entry.Property("UpdatedTime").CurrentValue = DateTime.Now;
            }
        }



        public virtual DbSet<Log> Log { get; set; }

        public virtual DbSet<Roles> Role { get; set; }
        public virtual DbSet<RolePermission> RolePermission { get; set; }

        public virtual DbSet<Users> User { get; set; }

        public virtual DbSet<UserRole> UserRole { get; set; }


        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSnakeCaseNamingConvention(); //适合PostgreSQL的蛇形命名
        }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
            //             .Where(t => t.GetInterfaces()
            //             .Any(gi => gi.IsGenericType && gi.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>)))
            //             .ToList();


            //foreach (Type type in typesToRegister)
            //{
            //    dynamic configurationInstance = Activator.CreateInstance(type);
            //    modelBuilder.ApplyConfiguration(configurationInstance);
            //}


            //var assembly = Assembly.GetExecutingAssembly();
            //var assembly = Assembly.Load("EF6.Entity");
            //foreach (Type type in assembly.ExportedTypes)
            //{
            //    if (type.IsClass && (type.Name != "xxx"))
            //    {
            //        var method = modelBuilder.GetType().GetMethods().Where(x => x.Name == "Entity").FirstOrDefault();
            //        if (method != null)
            //        {
            //            method = method.MakeGenericMethod(new Type[] { type });
            //            method.Invoke(modelBuilder, null);
            //        }
            //    }
            //}
            //base.OnModelCreating(modelBuilder);



            //启用Guid主键类型扩展
            //modelBuilder.HasPostgresExtension("uuid-ossp");

            base.OnModelCreating(modelBuilder);



            //foreach (var entityType in modelBuilder.Model.GetEntityTypes())
            //{
            //    entityType.
            //}
        }
    }
}
